package com.zone.trigger.job;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.zone.domain.strategy.model.valobj.AwardStockSubTaskVO;
import com.zone.domain.strategy.repository.IStrategyRepository;
import com.zone.domain.strategy.service.IRaffleStock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: zongzi
 * @description: 更新奖品库存定时器
 * @date: 2024/6/15
 */
@Slf4j
@Component
public class UpdateStrategyAwardStockJob {
    @Autowired
    private IStrategyRepository strategyRepository;
    @Autowired
    private IRaffleStock raffleStock;

    //    @Scheduled(cron = "0/5 * *  * * ? ")   //每5秒执行一次
    @XxlJob("UpdateStrategyAwardStockJob")
    public void execute() {
        // todo 从redis延迟队列中获取库存扣减任务，更新数据入库的时候执行失败，会导致数据库的库存未更新，从而引起“少卖”。
        try {
            AwardStockSubTaskVO awardStockSubTaskVO = raffleStock.pollAwardStockSubTask();
            if (Objects.isNull(awardStockSubTaskVO)) {
                return;
            }
            strategyRepository.decrStrategyAwardCountSurplus(awardStockSubTaskVO.getStrategyId(), awardStockSubTaskVO.getAwardId());
        } catch (Exception e) {
            log.warn("库存扣减定时器执行异常", e);
        }
    }
}
